package com.jpyl.jpMedicalTreatment.view.fragment.common;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.google.gson.JsonObject;
import com.jpyl.jpMedicalTreatment.R;
import com.jpyl.jpMedicalTreatment.model.ErrorMessageModel;
import com.jpyl.jpMedicalTreatment.model.NewsMessageModel;
import com.jpyl.jpMedicalTreatment.model.ResponseModel;
import com.jpyl.jpMedicalTreatment.network.Network;
import com.jpyl.jpMedicalTreatment.network.api.ApiError;
import com.jpyl.jpMedicalTreatment.network.api.RequestApi;
import com.jpyl.jpMedicalTreatment.view.activity.news.NewDetailsActivity;
import com.jpyl.jpMedicalTreatment.view.adapter.NewsAdapter;
import com.jpyl.jpMedicalTreatment.view.fragment.BaseFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 新闻
 * Created by 521546564465 on 2018/11/5.
 */

@SuppressLint("ValidFragment")
public class NewsFragment extends BaseFragment {


    @BindView(R.id.rv_refresh_layout)
    RecyclerView rvRefreshLayout;
    @BindView(R.id.mr_refresh_layout)
    MaterialRefreshLayout mrRefreshLayout;
    @BindView(R.id.tv_refreshLayout_Empty)
    TextView tvRefreshLayoutEmpty;
    Unbinder unbinder;
    NewsAdapter adapter;
    private List<NewsMessageModel.NewsModel> rows = new ArrayList<>();


    @SuppressLint("ValidFragment")
    public NewsFragment(Context context) {
        // TODO Auto-generated constructor stub
        super(context);
    }

    final RequestApi publicApi = Network.getRequestApi();
    int page = 1, listSize;

    @Override
    protected int getLayoutId() {
        return R.layout.news_fragment_layout;
    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        adapter = new NewsAdapter(rows);
        rvRefreshLayout.setAdapter(adapter);
        adapter.setItemClickListener(new NewsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                startActivity(new Intent(getContext(), NewDetailsActivity.class).putExtra("url",
                        rows.get(position).newsurl).putExtra("name", "新闻"));
            }
        });

        rvRefreshLayout.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        mrRefreshLayout.setLoadMore(true);
        mrRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                //刷新
                page = 1;
                jpylGetNews();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                super.onRefreshLoadMore(materialRefreshLayout);
                //加载更多
                if (listSize == 10) {
                    ++page;
                    jpylGetNews();
                } else {
                    materialRefreshLayout.finishRefreshLoadMore();
                }
            }
        });
        jpylGetNews();
    }


    private void jpylGetNews() {
        final JsonObject body = new JsonObject();
        body.addProperty("rows", "10");
        body.addProperty("page", page + "");

        publicApi.jpylGetNews(body.toString()).map(new Func1<ResponseModel<NewsMessageModel>,
                NewsMessageModel>() {
            @Override
            public NewsMessageModel call(ResponseModel<NewsMessageModel> responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<NewsMessageModel>() {

                    @Override
                    public void onCompleted() {
                        mrRefreshLayout.finishRefreshing();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshLoadMore();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        mrRefreshLayout.finishRefreshing();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshLoadMore();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                        }
                    }

                    @Override
                    public void onNext(NewsMessageModel model) {
                        mrRefreshLayout.finishRefreshing();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshLoadMore();
                        listSize = model.getTotal();
                        if (page == 1) {
                            rows.clear();
                        }
                        rows.addAll(model.getNews());
                        adapter.notifyDataSetChanged();
                    }
                });
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
